/**
 * Created by chengke on 2018/2/28.
 */

/**
 * Created by chengke on 2018/2/28.
 */

let FutuHttpClient = require('@futu/httpclient');
let FutuHttpRequest = FutuHttpClient.FutuHttpRequest;
let Campaign = require('../models/Campaign');

module.exports = CampaignService;

const BASE_API_URL = 'https://api.baidu.com/json/sms/service/CampaignService/';
const API_GET_CAMPAIGN = 'getCampaign';
const API_ADD_CAMPAIGN = 'addCampaign';
const API_UPDATE_CAMPAIGN = 'updateCampaign';
const API_DELETE_CAMPAIGN = 'deleteCampaign';

const CAMPAIGN_ATTRS = [
    'campaignId',
    'campaignName',
    'budget',
    'regionTarget',
    'negativeWords',
    'exactNegativeWords',
    'showProb',
    'device',
    'priceRatio',
    'pcPriceRatio',
    'pause',
    'status',
    'campaignType',
    'bidPrefer',
    'isDynamicCreative',
    'isDynamicTagSublink',
    'isDynamicTitle',
    'isDynamicHotRedirect',
];

/**
 * CampaignService
 *
 * @constructor
 * @param {String} username 用户名
 * @param {String} password 密码
 * @param {String} token API 令牌
 * @param {Object} options 扩展参数
 */
function CampaignService(username, password, token, options = {}) {
    this.username = username;
    this.password = password;
    this.token = token;
    this.options = options;
    this.commonHeader = {
        'username': this.username,
        'password': this.password,
        'token': this.token
    };
}

CampaignService.prototype.getCampaign = async function () {
    let result = await this._requestSemAPI(BASE_API_URL + API_GET_CAMPAIGN, {
        'campaignIds': [],
        'campaignFields': CAMPAIGN_ATTRS
    });
    if (result.header && result.header.status === 0) {
        return result.body.data;
    } else {
        return '';
    }
};

CampaignService.prototype.syncCampaign = async function () {
    let campaigns = await this.getCampaign();
    return campaigns.map(async function (item) {
        console.log(item);
        item.regionTarget = JSON.stringify(item.regionTarget);
        item.negativeWords = JSON.stringify(item.negativeWords);
        item.exactNegativeWords = JSON.stringify(item.exactNegativeWords);
        item.budgetOfflineTime = JSON.stringify(item.budgetOfflineTime);
        item.schedule = JSON.stringify(item.schedule);
        let campaign = await Campaign.findOne({
            where: {campaign_id: item.campaignId}
        });
        let result;
        if (campaign) {
            result = campaign.update(item);
        } else {
            result = await Campaign.create(item);
        }
        console.log(result);
    });
};

CampaignService.prototype.fullMockCategory = async function () {
    let campaigns = await Campaign.findAll();
    return await campaigns.map(async function (campaign) {
        campaign.categoryId = Math.floor(Math.random() * 16);
        return campaign.save();
    });
};

CampaignService.prototype._requestSemAPI = async function (url, body) {
    let client = await FutuHttpClient.getInstanceByEndpoint();
    let request = new FutuHttpRequest(url, {}, {});
    request.setIsJson(true);
    request.setData({
        'header': this.commonHeader,
        'body': body
    });
    let response = await client.request('post', request);
    if (response.httpStatusCode !== 200) {
        throw new Error('request ' + url + 'failed: ' + response.message);
    }
    return JSON.parse(response.data || '{}');
};
